// pages/onlineConsultation/onlineConsultation.js
var app = getApp();
//var util = require('../../utils/util.js');
Page({
  data: {
    news: '',
    scrollTop: 0,
    message: '',
    oldLength:"",
    news_input_val:'',
    contentData: [],
    contentData1:[/*{
      time: '2020-12-27 19:53',
      isRight:true,
      content: '医生我啥时候复诊哇',
      isImg: false,
    },
    {
      time: '2020-12-27 20:43',
      isRight: false,
      content: '上次我给你开的药吃完了吗？效果如何呢？',
      isImg: false,
    },
    {
      time: '2020-12-27 20:43',
      isRight:true,
      content: '../images/selectedMine.png',
      isImg: true,
    },*/
    ],
    selfImg: '../images/selectedMine.png',
    doctorId: '',
    doctorImg:'',
    doctorName:'',
    headOwner:'../images/selectedMine.png',
  },
  /**
   * 页面加载
   */
  onLoad: function (options) {
    this.setData({
      doctorId: options.doctorId,
      doctorName:options.doctorName,
    })
    console.log(options);
    wx.setNavigationBarTitle({ 
      title: this.data.doctorName
    });
    //this.getContent()
  },
  onShow:function(e){
   // var that=this;
   /* that.getMessage(); 
     setInterval(function () {
         that.getMessage(); 
        console.log("轮播请求1秒触发一次");
      }, 5000)*/
      this.getContent()
//slet _this = this;
      
      this.setData({
        timer: setInterval(() => {
          var that = this
          wx.request({
            url:  getApp().globalData.url + 'showpatientchatinfo',
            method: 'GET',
            data: {
              unitphone: getApp().globalData.unitphone,
              doctorId: that.data.doctorId,
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'  // 默认值
            },
            success(res){
              if(res.data.length!=that.data.oldLength)
              {
                that.getContent()
                that.bottom()
              }
            },})
          console.log("轮播请求10秒触发一次");
        }, 10000)
      })
     
      
      
    },
  /**
   * 输入消息
   */
  bindChange: function (e) {
    this.data.message = e.detail.value
  },
  onUnload:function(){
    clearInterval(this.data.timer);
		this.setData({
			timer: null
		})
  },
  onHide:function(){
    clearInterval(this.data.timer);
		this.setData({
			timer: null
		})
  },
  /**
   * 发送消息函数
   */
  send: function (e) {
    var that = this
    if(that.data.message!="")
    {
       wx.request({
      url:  getApp().globalData.url+'patientaddchatinfo',
      method: 'get',
      data: {
        unitphone: getApp().globalData.unitphone,
        doctorId: this.data.doctorId,
        content: this.data.message,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'  // 默认值
      },
      success(res){
        if (res.data == "1") {
          
          that.setData({
            message:'',
            inputValue:"",
            news_input_val:"",
          })
         that.getContent();
         that.bottom();
        } 
        else if(res.data=="0"){
          wx.showToast({
            title: '消息发送失败',
            icon: 'none',
          })
          
        }   
      },
      fail(res){
        wx.showToast({
          title: '网络连接中断，消息发送失败',
          icon: 'none',
        }) 
        
       
      }
    })
    }
   
  },

  /**
   * 获取聊天记录
   */ 
  getContent: function () {
    var that = this
    wx.request({
      url:  getApp().globalData.url + 'showpatientchatinfo',
      method: 'GET',
      data: {
        unitphone: getApp().globalData.unitphone,
        doctorId: that.data.doctorId,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'  // 默认值
      },
      success(res){
        if (res.data != "False" && res.data != "false" && res.data != false) {
          console.log(res.data)
          that.setData({
            selfImg:res.data[0].patientHeadLink,
            oldLength:res.data.length,
            doctorImg:res.data[0].doctorHeadLink,
          })
          let fi={};
          let first1=[];
         for(let i=0;i<res.data.length;i++) 
         {
             var messageTimes="";
             var isRights="";
             var contents="";
             var isImgs="";
             var urls="";
             messageTimes=res.data[i].chatTime;//发消息的时间
             //times=res.data[i].messageInform.bookDate + " " + res.data[i].messageInform.bookTime;
             isRights=res.data[i].isRight;
             isImgs=res.data[i].isImg;//消息类型（是否为图片）
             if(isImgs=="false")
             {
              contents=res.data[i].chatRecord.chatContent;
             }
             else{
              contents=res.data[i].chatRecord.photoLink;
             }
             console.log(res.data)
            fi={"time":messageTimes,"isRight":isRights,"content":contents,"isImg":isImgs};
            first1.push(fi);
         }
         that.setData({
          "contentData1":first1
        })
        console.log("插入的数据"+that.data.contentData1)
        that.bottom();
        } 
       /* else{
          wx.showToast({
            title: '消息获取失败，请下拉刷新',
            icon: 'none',
          })
        }  */ 
      },
      fail(res){
        wx.showToast({
          title: '网络连接中断，请下拉刷新',
          icon: 'none',
        })
       /* that.setData({
          selfImg:'../images/1.png',
        })
        let fi={};
        let first1=[];
        fi={"time":"2020-10-30","isRight":'false',"content": '../images/selectedMine.png',"isImg":"true"};
        first1.push(fi);
        fi={"time":"2020-10-30","isRight":'false',"content":'efwubc',"isImg":"false"};
        first1.push(fi);
        fi={"time":"2020-10-30","isRight":'true',"content":'efwugvhbnbc',"isImg":"false"};
        first1.push(fi);
        fi={"time":"2020-10-30","isRight":'false',"content": '../images/selectedMine.png',"isImg":"true"};
        first1.push(fi);
        fi={"time":"2020-10-30","isRight":'false',"content":'efwubc',"isImg":"false"};
        first1.push(fi);
        fi={"time":"2020-10-30","isRight":'true',"content":'efwugvhbnbc',"isImg":"false"};
        first1.push(fi);
        that.setData({
          "contentData1":first1
        })
        that.bottom();*/
      }
    })
  },
  /**
   * 获取hei的id节点然后屏幕焦点调转到这个节点 
   */ 
  bottom: function () {
    var query = wx.createSelectorQuery()
    query.select('#hei').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      wx.pageScrollTo({
        scrollTop: res[0].bottom  // #the-id节点的下边界坐标
      })
      res[1].scrollTop // 显示区域的竖直滚动位置
    })
  },

  /**
   * 选择图片并把图片保存  
   */  
  sendImg: function () {
    var that = this;
    wx.chooseImage({
      success: function (res) 
      {
        var tempFilePaths = res.tempFilePaths[0]
        wx.uploadFile({
          url: getApp().globalData.url + 'patientaddchatphoto',
          filePath: tempFilePaths,     
          name: 'filePhoto', //文件对应的参数名字(key)              
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          formData: {
           unitphone: getApp().globalData.unitphone,
           doctorId: that.data.doctorId,
          },
          success(res){
            if (res.data == "1") {
              that.getContent();
             
            } 
            else if(res.data=="0"){
              wx.showToast({
                title: '消息发送失败',
                icon: 'none',
              })
            }   
          },
          fail(res){
            wx.showToast({
              title: '网络连接中断，消息发送失败',
              icon: 'none',
            })
          }
        })
      }
    })
  }
})
